import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Navigate, useLocation } from 'react-router-dom';
import { Spin } from 'antd';
import { checkAuthState } from '../../store/slices/authSlice';

const PrivateRoute = ({ children }) => {
  const { isAuthenticated, loading, token } = useSelector((state) => state.auth);
  const location = useLocation();
  const dispatch = useDispatch();
  const [isChecking, setIsChecking] = useState(false);
  const [checkPerformed, setCheckPerformed] = useState(false);
  const [checkAttempts, setCheckAttempts] = useState(0);
  const MAX_CHECK_ATTEMPTS = 2; // 最大检查尝试次数
  
  useEffect(() => {
    // 只执行有限次数的认证状态检查，避免无限循环
    if (!checkPerformed && checkAttempts < MAX_CHECK_ATTEMPTS) {
      const localToken = localStorage.getItem('token');
      
      // 如果localStorage有token但Redux中没有，重新检查认证状态
      if (localToken && !token && !isChecking) {
        setIsChecking(true);
        setCheckAttempts(prev => prev + 1);
        
        dispatch(checkAuthState())
          .then(() => {
            setIsChecking(false);
            setCheckPerformed(true);
          })
          .catch(() => {
            setIsChecking(false);
            setCheckPerformed(true);
          });
      } else {
        setCheckPerformed(true);
      }
    }
  }, [dispatch, token, isChecking, checkPerformed, checkAttempts]);
  
  // 如果正在加载认证状态，显示加载中
  if (loading || isChecking) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <Spin size="large" />
        <span style={{ marginLeft: 8 }}>正在验证登录状态...</span>
      </div>
    );
  }
  
  // 如果超出最大检查次数但仍未通过验证，强制重定向到登录页
  if (checkAttempts >= MAX_CHECK_ATTEMPTS && !isAuthenticated) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }
  
  // 检查Redux状态和localStorage中是否有token
  const hasLocalToken = !!localStorage.getItem('token');
  
  // 使用Redux状态和localStorage双重验证
  if (!isAuthenticated && !hasLocalToken) {
    // 重定向到登录页面，并记住当前位置
    return <Navigate to="/login" state={{ from: location }} replace />;
  }
  
  // 已认证，显示受保护的内容
  return children;
};

export default PrivateRoute;